<?php
/*
 * 充值
 */
namespace Mobile\Controller;

use Mobile\Model\orderModel;
use Mobile\Model\moneylogModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\rechargeModel;//充值

use Mobile\Controller\PaywechatController;

class ChargeController extends BaseController {

    public $orderModel;
    public $memberModel;
    public $rechargeModel;
    public $moneylogModel;
    
    public function __construct() {
        parent::__construct();
        $this->orderModel = new orderModel();
        $this->moneylogModel = new moneylogModel();
    }
    
    
    /*
     * 账户充值
     */
    public function index(){
        $seo_data = array(
            "title" => C('CASH_NAME')."充值",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
    
        $share_data = array(
            "title" => C('CASH_NAME')."充值",
            "description" => "点击链接进行充值",
        );
        $this->setShare($share_data);
        
        $pay_to_caiwu = C("PAY_TO_CAIWU");//是否开启加财务微信充值
        if($pay_to_caiwu == 1){
            //财务人工充值
            $this->display("caiwu");
        }else{
            //自动充值
            parent::wxLogin();
            $this->display();
        }
    }
    
    public function chargescore(){
        $seo_data = array(
            "title" => C('SCORE_NAME')."充值",
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
    
        $share_data = array(
            "title" => C('SCORE_NAME')."充值",
            "description" => "点击链接进行充值",
        );
        if(IS_AJAX) {
            $allow = array('money','smscode');
            
            $data = param_filter($_POST, $allow);
            
            if(!$data['smscode']) {
                return_json(1,'请填写验证码');
            }
            
            if(session('SMSCODE')!=$data['smscode']) {
                return_json(1,'验证码不正确');
            }
            
            if($this->memberinfo['money']<$data['money']) {
                return_json(1,'佣金不足');
            }
            if($data['money']%1300!=0) {
                return_json(1,'充值金额必须是1300的倍数');
            } 
            $this->memberModel->where(array('uid'=>$this->memberinfo['uid']))->setDec('money',$data['money']);
            $this->memberModel->where(array('uid'=>$this->memberinfo['uid']))->setInc('score',$data['money']);
            $callback = new OrdercallbackController();
            $callback->handelChargeScore($this->memberinfo, $data['money'], 1);
            return_json(0,'充值成功','','/mobile/charge/chargescore');
        }
        $this->setShare($share_data);
        $pay_to_caiwu = C("PAY_TO_CAIWU");//是否开启加财务微信充值
        $this->display();
    }
    
    
    /*
     * 财务充值
     */
    public function caiwu(){
        header("Location:/mobile/charge");
    }
    
    
    /*
     * 支付成功显示页面
     */
    public function payok(){
    
        $order_id = get("order_id");
        if(!$order_id){
            $this->error2("支付失败");
        }
    
        $this->rechargeModel = new rechargeModel();
        $where = array(
            "uid" => $this->uid,
            "order_id" => $order_id,
        );
        $order = $this->rechargeModel->getRecharge($where);
        $this->assign("order",$order);
    
        $title = C("SITE_NAME");
        $seo_data = array(
            "title" => $title,
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        $this->setShare();
    
        $this->display();
    }
    
    
    protected function _get_recharge_data($money){
    
        $data['uid'] = $this->uid;
        $data['to_uid'] = $this->uid;//给自己充值
    
        $data['openid'] = $this->memberinfo['openid'] ? $this->memberinfo['openid'] : $this->openid;
        $data['nickname'] = $this->memberinfo['nickname'];
        $data['order_sn'] = 'CZ'.date("YmdHis").sprintf("%05d", $this->uid).rand(10,99);//生成订单号
        $data['pay_money'] = $data['pay_nowmoney'] = $data['pay_orgmoney'] = $money;
        $data['pay_type'] = 1;//微信支付
        $data['checked'] = 0;//等待付款
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['order_title'] = "账户充值";//第一件商品的商品名称
        
        $data['order_ip'] = get_client_ip();
    
        return $data;
    }
    
    /*
     * 生成微信支付信息
     * 1订单,2充值
     */
    protected function _get_wechatpay($order){
        
        $notify_url = get_domain()."/mobile/charge/callback/order_id/".$order['order_id'];// 异步通知地址

        $wechatpay = new PaywechatController();
        $wechatpay->setParameter("notify_url", $notify_url);//通知URL
        $wechatpay->setParameter("body", "充值订单:".$order['order_sn']);//商品描述
        $wechatpay->setParameter("out_trade_no", $order['order_sn']);//商户订单号
        $wechatpay->setParameter("total_fee", $order['pay_money']*100);//订单总金额,单位为分
        $wechatpay->setParameter("spbill_create_ip", $order['order_ip']);//客户ip地址
        $wechatpay->setParameter("openid","$this->openid");//
        $wechatpay->setParameter("trade_type","JSAPI");//
        $jsApiParameters = $wechatpay->getPayCode();
    
        return $jsApiParameters;
    }
    
    
    
    /*
     * 生成充值订单ajax
     */
    public function chargeajax(){
    
        if(!IS_AJAX){
            return_json(1,"请求方式有误");
        }
    
        $money = $_POST['money'];
        $money = $money*100;//换算成分
        if($money<1){
            return_json(1,"充值金额必须大于0");
        }
    
        if($money>5000000){
            return_json(1,"充值金额不能超过5万元");
        }
    
        //生成充值订单
        $order_data = $this->_get_recharge_data($money/100);//获取订单信息
    
        //将数据插入到订单表
        $rechargeModel = new rechargeModel();
        
        $order_data['ostype'] = 1;///1充值,2转账 3.红包
        
        $order_id = $rechargeModel->addRecharge($order_data);
    
        if(!$order_id){
            return_json(1,"创建订单失败");
        }
    
        $order_data['order_id'] = $order_id;
    
        $json = $this->_get_wechatpay($order_data);//获取支付信息
        $jsApiParameters = json_decode($json,true);
        
    
        if(!$jsApiParameters){
            return_json(1,"创建支付信息失败");
        }
    
        return_json(0,"请稍后...",$jsApiParameters,$order_id);
    
    }
    
    //充值后支付回调  后台
    public function callback(){
    
    
        $order_id = get('order_id');
        if(!$order_id){
            echo "fail";exit;
        }
    
        $where = array(
            "order_id" => $order_id,
        );
        //查找订单
        $this->rechargeModel = new rechargeModel();
    
        $order = $this->rechargeModel->getRecharge($where);
        if(empty($order)){
            echo "fail";exit;
        }
    
        $wechatpay = new PaywechatController();
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        
        file_put_contents("charge1.txt",$xml,FILE_APPEND);
        
        $xml_arr = $wechatpay->xmlToArray($xml);
    
        $res = $wechatpay->checkSign($xml_arr);
    
        if($res == FALSE){
            $r['return_code'] = 'FAIL';
            $r['return_msg'] = '签名失败';
            $a = "签名失败".$order['order_id'];
        }else{
            $r['return_code'] = 'SUCCESS';
            $r['return_msg'] = 'OK';
            $a = "签名正确".$order['order_id'];
        }
        echo $wechatpay->arrayToXml($r);
    
        if($res){
            if ($xml_arr["result_code"] == "SUCCESS") {
                //更改订单状态
                if($order['checked'] == 0){
                    //待支付,更改状态为已支付
                    $this->_changeRecharge($order,$xml_arr);//更改订单状态为已经完成
                }
    
                $a = "支付成功".$order['order_id'];
    
            }else{
                $a = "支付失败".$order['order_id'];
            }
        }
        file_put_contents("charge.txt",$a.$xml,FILE_APPEND);exit;
    
    }
    
    
    //更改订单状态
    /*
     * $xml_arr 微信传过来的参数
     * $status  0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,
     */
    protected function _changeRecharge($order,$xml_arr=null){
    
        $where = array(
            "order_id" => $order['order_id']
        );
    
        if(!empty($xml_arr)){
            $pay_type = 1;
            $is_subscribe = $xml_arr['is_subscribe'];// Y
        }else{
            //TODO
            $pay_type = 0;
            $is_subscribe = 'N';
        }
    
        $order_data = array(
            "checked" => 2,//已完成
            "pay_time" => date("Y-m-d H:i:s"),
            "pay_type" => $pay_type,//微信支付TODO
        );
    
        $order_res = $this->rechargeModel->editRecharge($where, $order_data);
    
        if(!$order_res){
            return false;
        }
        
        //更改状态成功
        //把钱写入余额
        $where_m = array(
            "uid" => $order['to_uid']
        );
        
        //充值
        $money = array(
            "cash_money" => array("exp","cash_money+".$order['pay_money'])
        );
        
        $res2 = $this->memberModel->editMember($where_m, $money);//把钱加上
        
        if(!$res2){
            return false;
        }
        
        //我的用户信息
        $toinfo = $this->getMemberInfobyUid($order['to_uid']);//收件方信息
        
        //写日志流水
        //写流水
        $data = array(
            "content" => $order['order_title'],
            "un_lock" => 1,//1解锁 ,0锁定, 现在都为解锁,直接到账
            "money" => $order['pay_money'],
            "from_jibie" => 0,
            "order_id" => $order['order_id'],
            "order_uid" => $order['uid'],
            "order_paymoney" => $order['pay_money'],
            "order_nickname" => $order['nickname'],
            "order_time" => $order['create_time'],//订单创建时间
            "pay_time" => date("Y-m-d H:i:s"),//订单支付时间
            "create_time" => date("Y-m-d H:i:s"),
            "uid" => $order['to_uid'],
            "nickname" => $toinfo['nickname'],
            "logtype" => 1,//收入
            "mtype" => 3,//1分销佣金,2重消币 3现金电子币 4重消佣金5互助奖6车房奖7领导奖8分红奖
            "cash_money" => $toinfo['cash_money'],//充值后的余额
            "note" => "微信充值",
            "is_charge" => 1,
            'un_lock' => 1
        );
        
        $res1 = $this->moneylogModel->addMoneylog($data);
        
        $this->_chargeMsg($toinfo,$order);//发送充值通知
        
        return $res1;
        
        
    
    }
    
    
    
    /*
     * 拼接模板消息
     */
    protected function _sendchargetmp($userinfo,$order){
    
        $tmp_id = $this->tmpl['CZ_OK']['tmp_id'];
		$color = $this->tmpl['CZ_OK']['color'];
    
        $url = get_domain()."/mobile/charge/payok/?order_id=".$order['order_id'];
        $footer ='\\n'."点击查看详情...";
    
        $title = "尊敬的用户，您已成功充值".C('CASH_NAME');

        
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($title),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($order['pay_money']),//金额
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),//充值时间
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($userinfo['cash_money']),//余额
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
    
    /*
     * 通知,模板消息
     * 1
     */
    protected function _chargeMsg($userinfo,$order){
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg = $this->_sendchargetmp($userinfo,$order);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
}